<template>
  <div class="select-tree">
    <el-popover
      ref="popover4"
      placement="bottom"
      v-model="treeShow"
      :disabled="disabled"
      :visible-arrow="false"
      trigger="click"
    >
      <el-tree
        class="el-tree1"
        ref="tree"
        node-key="key"
        :data="optionData"
        @node-click="nodeClick"
        :props="defaultProps"
        :highlight-current="true"
        accordion
        :filter-node-method="filterNode"
      >
      </el-tree>
    </el-popover>
    <el-form label-position="top" :rules="rules" ref="form" :model="form" class="padding-b">
      <el-form-item :label="label" prop="value">
        <el-input
          size="mini"
          :placeholder="placehoder.length > 0 ? placehoder.join('-->'): placeholderNew"
          v-model.trim="form.value"
          v-popover:popover4
          :disabled="disabled"
        >
        </el-input>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getDicFromField } from '@/utils/workflowUtils'
export default {
  name: 'optionsTree',
  data() {
    let self = this
    let validate1 = (rule, value, callback) => {
      let node = self.getNode(self.checked[self.checked.length - 1])
      // 如果是叶子节点则必填校验通过
      if (node && node.isLeaf) {
        callback()
      } else if (self.require === 'no') {
        callback()
      } else {
        callback(new Error(this.$t('validate.required')))
      }
    }
    return {
      optionData: [],
      checked: [],
      placehoder: [],
      treeShow: false,
      cascade: '',
      form: {
        value: ''
      },
      defaultProps: {
        children: 'options',
        label: 'name'
      },
      rules: {
        value: [{ validator: validate1, required: this.require === 'required', trigger: 'blur' }]
      }
    }
  },
  props: {
    label: String,
    default: { type: Array },
    id: String,
    dic: '',
    disabled: { type: String | Boolean, default: false },
    placeholderNew: { type: String, default: '' },
    require: String,
    random: { type: Number, default: 0 },
    field: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  computed: {},
  watch: {
    'form.value'(val) {
      // if (val) {
      //   this.treeShow = true
      //   this.$refs.tree.filter(val)
      // } else {
      //   this.$refs.tree.filter(val)
      //   this.treeShow = false
      // }
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    submit(noCheck) {
      // noCheck为true 不进行校验
      let obj = {}
      if (noCheck) {
        obj.success = true
      } else {
        this.$refs.form.validate((valid) => {
          obj.success = valid
        })
      }
      if (obj.success) {
        obj.data = {}
        for (let i = 0; i < this.cascade; i++) {
          if (!i) {
            obj.data[this.id] = this.checked[i] || ''
          } else {
            obj.data[this.id + '_' + i] = this.checked[i] || ''
          }
        }
      }
      return obj
    },
    nodeClick(data, node, self) {
      if (node.isLeaf) {
        this.treeShow = false
        this.form.value = ''
        this.checked = []
        this.placehoder = []
        this.checkPick(node)
        this.$refs.form.validate()
        this.$emit('blurEvent', this.submit(true))
      }
    },
    checkPick(node) {
      if (node && node.parent) {
        this.placehoder.unshift(node.data.name)
        this.checked.unshift(node.data.key)
        this.checkPick(node.parent)
      }
    },
    filterPick(node, value) {
      let isShow = node.data.name.indexOf(value) !== -1
      if (isShow) {
        return true
      }
      // 带英文大小写的情况  新加一段代码 保证不影响之前的逻辑 start ===========
      if (value && node.data && node.data.name) {
        let valueCase = value.toLowerCase()
        let nameCase = node.data.name.toLowerCase()
        isShow = nameCase.indexOf(valueCase) !== -1
      }
      if (isShow) {
        return true
      }
      // ===========================================end   ===========================
      if (node.parent && node.level !== 1) {
        let result = this.filterPick(node.parent, value)
        if (result) {
          return true
        }
      }
    },
    getNode(key) {
      return this.$refs.tree.getNode(key)
    },
    setCheckedKeys() {
      this.$refs.tree.setCurrentKey(this.checked[4])
    },
    filterNode(value, data, node) {
      // if (!value) return true
      // return data.label.indexOf(value) !== -1
      return this.filterPick(node, value)
    },
    handleData() {
      // 初始化级联数据  和 级联初始值
      let options = (this.options =
        getDicFromField(this.field, this.$getCache('custTmpls'), this.$getCache('options')) || {})
      this.cascade = parseInt(options.cascade)
      this.optionData = options.options
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.checked = this.default.filter((item) => item)
      if (this.checked.length) {
        let node = this.getNode(this.checked[this.checked.length - 1])
        this.checked = []
        this.placehoder = []
        this.checkPick(node)
      }
    })
  },
  beforeMount() {
    this.handleData()
  }
}
// 递归options数据 转化成级联数据
// function updateOptions (options, arg) {
//   for (let i = 0; i < options.length; i++) {
//     const ele = options[i]
//     let obj = {
//       children: [],
//       label: ele.name,
//       value: ele.key
//     }
//     arg.Arr.push(obj)
//     ele.options = ele.options || []
//     ele.options.length > 0 ? updateOptions(ele.options, {Arr: obj.children}) : delete obj.children
//   }
// }
</script>
<style lang="stylus">
.select-tree .el-tree1 .el-tree-node >.el-tree-node__children
  overflow visible
.select-tree input::-webkit-input-placeholder
  color #737373 !important
</style>
<style lang="stylus" scoped>
 @import "../../../../../assets/common.styl"
.el-checkbox
  padding-right 0
.padding-b
  max-width 400px
.el-tree1
  padding-bottom 5px
  max-height 280px
  max-width 600px
  min-width 250px
  overflow auto
  border none
</style>
